package com.java.simple.study.juc.p5;

import com.java.simple.study.tool.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author zhoujunlin
 * @date 2022年07月01日 21:45
 * @desc 21:53:50.189 c.ABAProblem [main] - main start...
 * 21:53:50.252 c.ABAProblem [t1] - change A->B true
 * 21:53:51.255 c.ABAProblem [t2] - change B->A true
 * 21:53:53.256 c.ABAProblem [main] - change A ->C true
 */
@Slf4j(topic = "c.ABAProblem")
public class ABAProblem {

    static AtomicReference<String> ref = new AtomicReference<>("A");

    public static void main(String[] args) {
        log.debug("main start...");
        // 获取值A
        // 这个共享变量被其他线程修改过？
        String mainPrev = ref.get();
        // A->B   B->A
        other();
        Sleeper.sleep(2);
        // 尝试修改为C
        // 可以修改成功
        log.debug("change A ->C {}", ref.compareAndSet(mainPrev, "C"));
    }

    private static void other() {
        new Thread(() -> {
            log.debug("change A->B {}", ref.compareAndSet(ref.get(), "B"));
        }, "t1").start();
        Sleeper.sleep(1);
        new Thread(() -> {
            log.debug("change B->A {}", ref.compareAndSet(ref.get(), "A"));
        }, "t2").start();
    }


}
